package com.lyq.demo.redis.service;

import com.lyq.demo.redis.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lyq
 * @time 2019/5/12 10:24
 */
@Service
@Slf4j
public class OrderService {

    private List<Order> orders;

    @PostConstruct
    public void init(){
        orders = new ArrayList<>();
        orders.add(new Order(1,"AAA"));
        orders.add(new Order(2,"BBB"));
        orders.add(new Order(3,"CCC"));
        orders.add(new Order(4,"DDD"));
        orders.add(new Order(5,"EEE"));
    }


    @Cacheable(value = "orderCache",key = "#id")
    public Order getById(Integer id){
        log.info("查询数据库，id={}的订单",id);
        for (Order order : orders) {
            if(order.getId().intValue() == id){
                return order;
            }
        }
        return null;
    }

    @CachePut(value = "orderCache",key = "#id")
    public Order updateById(Integer id,String name){
        log.info("更新数据库，id={}的order",id);
        for (Order order : orders) {
            if(order.getId().intValue() == id){
                order.setOrderName(name);
                return order;
            }
        }
        return null;
    }

    @CacheEvict(value = "orderCache",key = "#id")
    public void deleteById(Integer id){
        log.info("删除数据库，id={}的order",id);
        int index = -1;
        for (Order order : orders) {
            if(order.getId().intValue() == id){
                index = orders.indexOf(order);
            }
        }
        if(index > -1){
            orders.remove(index);
        }
    }
}
